document.addEventListener('DOMContentLoaded', function() {
    LoadUserData();
    LoadCourseData();
    LoadUnitData();
    initUnitDeleteEvent();
    $(document).off('click', '.edit-unit-btn').on('click', '.edit-unit-btn', handleEditUnit);
});

//单元管理板块
function LoadUnitData() {
    $.ajax({
        url: 'http://localhost:9220/AttendanceSystem/UnitInfoController',
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            console.log('单元数据加载成功:', data);
            renderUnitTable(data);

        },
        error: function(xhr) {
            console.error('单元数据加载失败:', xhr.responseText);
            showToast('单元数据加载失败', 'error');
        }
    });
}

// 表格渲染函数
function renderUnitTable(units) {
    const $tableBody = $('.unit-data-table tbody');
    $tableBody.empty();

    units.forEach(unit => {
        const row = `
            <tr data-unit-id="${unit.unitId}">
                <td>${unit.unitName}</td>
                <td class="ellipsis" title="${unit.unitDescription}">${unit.unitDescription}</td>
                 <td>${unit.courseId || '未关联课程'}</td>
                <td>${unit.unitDuration}小时</td>
               
                <td>
                    <button class="edit-unit-btn"
                            data-id="${unit.unitId}"
                            data-name="${unit.unitName}"
                            data-desc="${unit.unitDescription}"
                            data-duration="${unit.unitDuration}"
                            data-course="${unit.courseId}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="delete-unit-btn"
                            data-id="${unit.unitId}"
                            data-name="${unit.unitName}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            </tr>`;
        $tableBody.append(row);
    });
}
// 绑定新增单元按钮点击事件
document.querySelector('[data-target="add-unit"]').addEventListener('click', function() {
    // 显示模态框
    const modal = document.getElementById('add-unit-modal');
    modal.style.display = 'block';

    // 初始化课程选择器
    if (modal.querySelector('.course-select').hasChildNodes()) {

        initCourseSelect(modal);
    }
});

// // 初始化课程选择器（复用课程管理的函数）
function initCourseSelect(modal) {
    console.log('课程数据加载成功:', modal);
    $.get('http://localhost:9220/AttendanceSystem/CourseInfoController', function(courses) {

        const $select = $(modal).find('.course-select');
        $select.empty().append('<option value="">请选择课程</option>');
        courses.forEach(course => {
            $select.append(`<option value="${course.courseId}">${course.courseName}</option>`);
        });
    });
}

// 关闭模态框（复用现有逻辑）
document.querySelectorAll('#add-unit-modal .modal-close, #add-unit-modal .btn-cancel').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('add-unit-modal').style.display = 'none';
    });
});

// 表单提交处理
document.getElementById('unit-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = {
        unitName: $('input[name="unitName"]').val().trim(),
        unitDesc: $('textarea[name="unitDesc"]').val().trim(),
        unitDuration: parseFloat($('input[name="unitDuration"]').val()),
        courseId: $('select[name="courseId"]').val()
    };
    console.log('提交数据:', formData);

    $.ajax({
        url: 'http://localhost:9220/AttendanceSystem/AddUnitController',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {

                showToast('单元添加成功', 'success');
                LoadUnitData();  // 刷新单元列表
                document.getElementById('add-unit-modal').style.display = 'none';

        },
        error: function(xhr) {
            console.error('添加失败:', xhr.responseText);
            showToast('添加失败，请检查数据格式', 'error');
        }
    });
});


// 绑定删除按钮事件（在DOMContentLoaded中调用）
function initUnitDeleteEvent() {
    $(document).on('click', '.delete-unit-btn', function() {
        const unitId = $(this).data('id');
        const unitName = $(this).data('name');

        if (!confirm(`确定要删除【${unitName}】单元吗？`)) return;

        $.ajax({
            url: `http://localhost:9220/AttendanceSystem/DeleteUnitController?unitId=${unitId}`,
            method: 'DELETE',
            success: function(response) {
                    showToast('单元删除成功', 'success');
                    LoadUnitData(); // 刷新单元列表

            },
            error: function(xhr) {
                console.error('删除失败:', xhr.responseText);
                showToast('删除失败，请稍后重试', 'error');
            }
        });
    });
}

// 修改单元
document.addEventListener('DOMContentLoaded', function() {
    $(document).on('click', '.edit-unit-btn', handleEditUnit);
});
const editUnitModalHTML = `<div class="modal" id="edit-unit-modal">
    <div class="modal-overlay"></div>
    <div class="modal-container">
        <div class="modal-header">
            <h3><i class="fas fa-book-open"></i> 编辑教学单元</h3>
            <button type="button" class="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <form id="edit-unit-form">
                <input type="hidden" id="edit-unit-id">
                <div class="form-group">
                    <label>单元名称</label>
                    <input type="text" name="upunitName" required
                        
                           title="5-50个字符">
                </div>
                <div class="form-group">
                    <label>单元描述</label>
                    <textarea name="upunitDesc" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label>课时时长</label>
                    <input type="number" name="upunitDuration"
                           min="1" max="10" step="0.5" required>
                </div>
                <div class="form-group">
                    <label>关联课程</label>
                    <select name="upcourseId" class="course-select" required>
                        <option value="">请选择课程</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-cancel">取消</button>
                    <button type="submit" class="btn btn-primary">保存修改</button>
                </div>
            </form>
        </div>
    </div>
</div>`;
document.body.insertAdjacentHTML('beforeend', editUnitModalHTML);

// 处理编辑按钮点击
function handleEditUnit() {
    const modal = document.getElementById('edit-unit-modal');
    if (modal.querySelector('.course-select').hasChildNodes()) {

        initCourseSelect(modal);
    }

    const unitData = {
        id: $(this).data('id'),
        name: $(this).data('name'),
        desc: $(this).data('desc'),
        duration: $(this).data('duration'),
        courseId: $(this).data('course')
    };

    // 初始化模态框

    // 填充数据
    $('#edit-unit-form input[name="upunitName"]').val(unitData.name);
    $('#edit-unit-form textarea[name="upunitDesc"]').val(unitData.desc);
    $('#edit-unit-form input[name="upunitDuration"]').val(unitData.duration);
    $('#edit-unit-form select[name="upcourseId"]').val(unitData.courseId);
    $('#edit-unit-id').val(unitData.id);
    // $('body').append(editUnitModalHTML);


    $('#edit-unit-modal').fadeIn();
}

// 绑定表单提交

    $('#edit-unit-form').submit(function (e) {
        e.preventDefault();

        const unitId = $('#edit-unit-id').val();
        console.log('单元ID:', unitId);
        const formData = {
            unitName: $('input[name="upunitName"]').val().trim(),
            unitDesc: $('textarea[name="upunitDesc"]').val().trim(),
            unitDuration: parseInt($('input[name="upunitDuration"]').val()),
            courseId: $('select[name="upcourseId"]').val()
        };
        console.log('提交数据:', formData);

        $.ajax({
            url: `http://localhost:9220/AttendanceSystem/UpdateUnitController?unitId=${unitId}`,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                    showToast('单元更新成功', 'success');
                    $('#edit-unit-modal').fadeOut();
                    LoadUnitData();

            },
            error: function(xhr) {
                console.error('更新失败:', xhr.responseText);
                showToast('更新失败，请检查数据格式', 'error');
            }
        });
    });

    // 关闭模态框
    $(document).off('click', '#edit-unit-modal .modal-close, #edit-unit-modal .btn-cancel')
        .on('click', '#edit-unit-modal .modal-close, #edit-unit-modal .btn-cancel', function() {
            console.log('关闭模态框');
            $('#edit-unit-modal').fadeOut();
        });











//课程管理板块
function LoadCourseData(){
    $.ajax({
        url: 'http://localhost:9220/AttendanceSystem/CourseInfoController',
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            console.log('课程数据加载成功:', data);
            // 清空课程表格（假设表格类名为course-table）
            $('.course-data-table tbody').empty();

            data.forEach(course => {
                const row = `                    
                    <tr data-course-id="${course.id}">
                        <td>${course.courseCode}</td>
                        <td>${course.courseName}</td>
                        <td>${course.credit}</td>
                
                        <td>${course.teacherId}</td>
                        <td>
                            <button class="edit-course-btn" 
                                    data-course-Id="${course.courseId}"
                                    data-course-Code="${course.courseCode}"
                                    data-course-Name="${course.courseName}"
                                    data-credit="${course.credit}"
                                    data-teacher-Id="${course.teacherId}">
                                <i class="fas fa-edit"></i> 修改
                            </button>
                            <button class="delete-course-btn" 
                                    data-id="${course.id}"
                                    data-name="${course.name}">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </td>
                    </tr>`;
                $('.course-data-table tbody').append(row);
            });

            // 绑定操作按钮事件（需在全局事件监听器中添加）
            // $(document).on('click', '.edit-course-btn', handleEditCourse);

        },
        error: function(xhr, status, error) {
            console.error('课程数据加载失败:', {
                status: xhr.status,
                error: xhr.responseText
            });
            showToast('课程数据加载失败', 'error');
        }
    });
}
document.addEventListener('DOMContentLoaded', function() {
    $(document).on('click', '.delete-course-btn', handleDeleteCourse);
});
function handleDeleteCourse() {
    const courseId = $(this).data('id');
    const courseName = $(this).data('name');

    if (!confirm(`确定要删除课程【${courseName}】吗？此操作不可恢复！`)) return;

    $.ajax({
        url: `http://localhost:9220/AttendanceSystem/DeleteCourseController?courseId=${courseId}`,
        method: 'DELETE',
        success: function(response) {
            if(response.success) {
                showToast(`课程【${courseName}】已删除`, 'success');
                LoadCourseData(); // 刷新课程列表
            } else {
                showToast(response.message || '删除失败', 'error');
            }
        },
        error: function(xhr) {
            console.error('删除失败详情:', {
                status: xhr.status,
                response: xhr.responseText
            });
            showToast(`删除失败：${xhr.statusText}`, 'error');
        }
    });
}
document.addEventListener('DOMContentLoaded', function() {
    $(document).on('click', '.edit-course-btn', handleEditCourse);
});
const editCourseModalHTML = `<div class="modal" id="edit-course-modal">
    <div class="modal-overlay"></div>
    <div class="modal-container">
        <div class="modal-header">
            <h3><i class="fas fa-edit"></i> 修改课程信息</h3>
            <button class="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <form id="edit-course-form">
                <input type="hidden" id="edit-course-id">
                <div class="form-group">
                    <label>课程代码</label>
                    <input type="text" name="upCourseCode" required 
                  
                           title="格式示例：AB123">
                </div>
                <div class="form-group">
                    <label>课程名称</label>
                    <input type="text" name="upCourseName" required>
                </div>
                <div class="form-group">
                    <label>学分</label>
                    <select name="upCredit" required>
                        <option value="1">1学分</option>
                        <option value="2">2学分</option>
                        <option value="3">3学分</option>
                        <option value="4">4学分</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>授课教师</label>
                    <input type="text" name="upTeacher" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-cancel">取消</button>
                    <button type="submit" class="btn btn-primary">保存修改</button>
                </div>
            </form>
        </div>
    </div>
</div>`;
document.body.insertAdjacentHTML('beforeend', editCourseModalHTML);
function handleEditCourse() {
    const courseData = {
        id: $(this).data('courseId'),
        code: $(this).data('courseCode'),
        name: $(this).data('courseName'),
        credit: $(this).data('credit'),
        teacher: $(this).data('teacherId')

    };

    $('#edit-course-form input[name="upCourseCode"]').val(courseData.code);
    $('#edit-course-form input[name="upCourseName"]').val(courseData.name);
    $('#edit-course-form select[name="upCredit"]').val(courseData.credit);
    $('#edit-course-form input[name="upTeacher"]').val(courseData.teacher);
    $('#edit-course-id').val(courseData.id);
    // 显示模态框
    $('#edit-course-modal').fadeIn();
}
// 处理保存修改事件
$('#edit-course-form').submit(function(e) {
    e.preventDefault();

    const courseId = $('#edit-course-id').val();
    const formData = {
        courseCode: $('input[name="upCourseCode"]').val().trim(),
        courseName: $('input[name="upCourseName"]').val().trim(),
        credit: $('select[name="upCredit"]').val(),
        teacher: $('input[name="upTeacher"]').val().trim()
    };
    console.log('修改课程信息：', formData);

    // 发送更新请求
    $.ajax({
        url: `http://localhost:9220/AttendanceSystem/UpdateCourseController?courseId=${courseId}`,
        method: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if(response.success) {
                showToast('课程修改成功', 'success');
                $('#edit-course-modal').fadeOut();
                LoadCourseData(); // 刷新列表
            } else {
                showToast(response.message || '修改失败', 'error');
            }
        },
        error: function(xhr) {
            console.error('修改失败:', xhr.responseText);
            showToast(`修改失败：${xhr.statusText}`, 'error');
        }
    });
});

// 关闭模态框
$('#edit-course-modal .modal-close, #edit-course-modal .btn-cancel').click(() => {
    $('#edit-course-modal').fadeOut();
});

// 用户板块
function LoadUserData(){
    $.ajax(
        {
            url:`http://localhost:9220/AttendanceSystem/UserInfoController`,
            method:"get",
            dataType: "json",
            success:function (data) {
                $('.data-table tbody').empty();
                data.forEach(user => {
                    const row = `                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.role}</td>
                        <td>
                            <button type="button" class="edit-btn" data-id="${user.id}" data-name="${user.username}" data-role="${user.role}">查看</button>
                            <button type="button" class="delete-btn" data-id="${user.id}">删除</button>
                        </td>
                    </tr>
                `;
                    $('.data-table tbody').append(row);
                });
                // 绑定操作按钮事件
                // $('.edit-btn').click(handleEdit);
            },
            error:function (error,xhr,status) {
                console.error("请求失败详情:", {
                    "状态码": xhr.status,
                    "状态": status,
                    "响应内容": xhr.responseText
                });
            }
        }
    )
}
document.addEventListener('DOMContentLoaded', function() {
    $(document).on('click', '.delete-btn', handleDelete);
});

function handleDelete() {
    const userId = $(this).data('id');
    console.log('User ID to delete:', userId);

    if (!confirm('确定要删除该用户吗？')) return;

    $.ajax({
        url: `http://localhost:9220/AttendanceSystem/DeleteUserController?id=${userId}`,
        method: 'DELETE',
        success: function(response) {
            LoadUserData(); // 刷新数据
            showToast('用户删除成功', 'success');
        },
        error: function(xhr) {
            console.error('删除失败:', xhr.responseText);
            showToast('删除失败', 'error');
        }
    });
}
document.addEventListener('DOMContentLoaded', function() {
    $(document).on('click', '.edit-btn', handleEdit);
});
function handleEdit() {
    const userName=$(this).data('name');
    const role=$(this).data('role');

    $.ajax(
        {
            url:'http://localhost:9220/AttendanceSystem/DetailUserController',
            method:'POST',
            contentType: 'application/json',
            data: JSON.stringify({ userName, role}),
                success:function (response) {
                    if(response.status === 'success') {
                        console.log('获取信息成功:', response.data);
                        showEditModal(response.data, response.role);
                    } else {
                        showToast('获取信息失败', 'error');
                    }
            },
            error:function (error,xhr,status) {
                console.error("请求失败详情:", {
                    "状态码": xhr.status,
                    "状态": status,
                    "响应内容": xhr.responseText
                });
            }
        }
    )
}
function showEditModal(data, role) {
    // 生成不同角色的表单模板
    const formHtml = `
        <div class="modern-modal" id="edit-user-modal">
            <div class="modal-overlay"></div>
            <div class="modal-container">
                <div class="modal-header">
                    <h3><i class="fas fa-edit"></i> 查看${getRoleName(role)}信息</h3>
                    <button class="modal-close">&times;</button>
                </div>
                <div class="modal-body">
                    ${generateFormFields(data, role)}
                </div>
            </div>
        </div>
    `;

    // 插入并显示模态框
    $('body').append(formHtml);
    $('#edit-user-modal').fadeIn();

    // 绑定关闭事件
    $('#edit-user-modal .modal-close, .btn-cancel').click(() => {
        $('#edit-user-modal').remove();
    });
}

// 辅助函数：生成不同角色的表单字段
function generateFormFields(data, role) {
    let fields = `    <div class="form-group">
        <label>${role === 'ADMIN' ? '管理员账号' : '用户名'}</label>
        <input type="text" value="${role === 'ADMIN' ? data.username : data.name}" readonly>
    </div>`;

    switch(role) {
        case 'TEACHER':
            fields += `
                <div class="form-group">
                    <label>工号</label>
                    <input type="text" value="${data.employeeId}">
                </div>
                <div class="form-group">
                    <label>部门</label>
                    <input type="text" value="${data.department}">
                </div>
                <div class="form-group">
                    <label>职称</label>
                    <input type="text" value="${data.title}">
                </div>
                <div class="form-group">
                    <label>邮箱</label>
                    <input type="text" value="${data.email}">
                </div>
                <div class="form-group">
                    <label>电话</label>
                    <input type="text" value="${data.phone}">
                </div>
                <div class="form-group">
                    <label>办公室</label>
                    <input type="text" value="${data.office}">
                </div>`
            break;
        case 'STUDENT':
            fields += `
                <div class="form-group">
                    <label>学号</label>
                    <input type="text" value="${data.id}">
                </div>
                 <div class="form-group">
                    <label>学院</label>
                    <input type="text" value="${data.college}">
                </div>
                <div class="form-group">
                    <label>班级</label>
                    <input type="text" value="${data.className}">
                </div>`;
            break;
        case 'ADMIN':
            fields += `
             <div class="form-group">
                    <label>全名</label>
                    <input type="text" value="${data.fullName}">
                </div>
             <div class="form-group">
                    <label>部门</label>
                    <input type="text" value="${data.department}">
             </div>
             <div class="form-group">
                    <label>电话</label>
                    <input type="text" value="${data.contactPhone}">
                </div>
             <div class="form-group">
                    <label>邮箱</label>
                    <input type="text" value="${data.email}">
                </div>
             <div class="form-group">
                    <label>办公室</label>
                    <input type="text" value="${data.office}">
                </div>`;

            break;
    }

    return fields ;
}

// 辅助函数：获取角色中文名称
function getRoleName(role) {
    return {
        'TEACHER': '教师',
        'STUDENT': '学生',
        'ADMIN': '管理员'
    }[role];
}
// 在DOMContentLoaded事件监听器中添加按钮点击事件

document.getElementById('add-user').addEventListener('click', function() {
    // 创建动态表单
    const formHtml = `
        <div class="modern-modal" id="add-user-modal">
    <div class="modal-overlay"></div>
    <div class="modal-container">
        <div class="modal-header">
            <h3 class="modal-title"><i class="fas fa-user-plus"></i> 添加新用户</h3>
            <button class="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <form id="user-form" class="modern-form">
                <div class="form-group animated-input">
                    <input type="text" name="username" required>
                    <label>用户名</label>
                    <i class="fas fa-user"></i>
                </div>
                
                <div class="form-group animated-input">
                    <input type="password" name="password" required>
                    <label>初始密码</label>
                    <i class="fas fa-lock"></i>
                </div>

                <div class="form-group select-wrapper">
                    <label><i class="fas fa-user-tag"></i> 用户角色</label>
                    <select name="role" required>
                        <option value="STUDENT">学生 👩🎓</option>
                        <option value="TEACHER">教师 👨🏫</option>
                        <option value="ADMIN">管理员 👨💼</option>
                    </select>
                </div>

                <div class="form-actions">
                    <button type="button" class="btn btn-cancel">取消</button>
                    <button type="button" class="btn btn-submit">
                        <i class="fas fa-plus-circle"></i> 创建用户
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
    `;

    // 插入模态框到页面
    document.body.insertAdjacentHTML('beforeend', formHtml);

    // 显示模态框
    const modal = document.getElementById('add-user-modal');
    modal.style.display = 'block';

    // 关闭事件
    modal.querySelector('.modal-close').onclick = () => modal.remove();
    modal.querySelector('.btn-cancel').onclick = () => modal.remove();


    // 表单提交处理
    modal.querySelector('.btn-submit').addEventListener('click', function(e) {
        e.preventDefault();

        const form = document.getElementById('user-form');
        const formData = {
            username: form.username.value,
            password: form.password.value,
            role: form.role.value
        };
        console.log('Form data:', formData);

        $.ajax({
            url: 'http://localhost:9220/AttendanceSystem/AddUserController',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                modal.remove();
                LoadUserData();
                showToast('用户添加成功', 'success'); // 建议替换alert为更优雅的提示
            },
            error: function(xhr) {
                console.error('添加失败:', xhr.responseText);
                showToast('添加失败', `error`);
            },
        });
    });
});
// 显示新增课程模态框
document.querySelector('[data-target="add-course"]').addEventListener('click', function() {
    console.log('显示新增课程模态框');
    document.getElementById('add-course-modal').style.display = 'block';
});

// 关闭模态框
document.querySelectorAll('.modal-close, .btn-cancel').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('add-course-modal').style.display = 'none';
    });
});

// 表单提交处理
document.getElementById('course-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = {
        courseCode: $('input[name="courseCode"]').val().trim(),
        courseName: $('input[name="courseName"]').val().trim(),
        credit: $('select[name="credit"]').val(),
        teacher: $('input[name="teacher"]').val().trim()
    };

    // 这里添加Ajax提交代码（需要与后端接口对接）
    console.log('提交课程数据:', formData);
    $.ajax({
        url: 'http://localhost:9220/AttendanceSystem/AddCourseController',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            console.log('课程添加成功:', response);
            showToast('课程添加成功', 'success');
            LoadCourseData();
        },
        error: function(xhr) {
            console.error('添加课程失败:', xhr.responseText);
            showToast('请输入正确的参数', 'error');
        }
    })
    // 示例：admAjax.addCourse(formData);
    document.getElementsByClassName('modal')[0].style.display = 'none';
    // this.reset();
    // this.parentElement.parentElement.style.display = 'none';
});


